import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, DatePicker, Badge, Select, Descriptions } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../DevLog/DevTask.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['等待设置', '设置中', '设置成功', '设置失败', '设置超时'];
const statusMap = ['default', 'processing', 'success', 'error'];
const setType = [
    '已绑定',
    '未绑定',
];

@connect(({ playlist, loading }) => ({
    playlist,
    loading: loading.models.playlist,
}))
@Form.create()
export default class PlayList extends PureComponent {
    state = {
        selectedRows: [],
        formValues: {},
    };

    componentDidMount() {
        const { dispatch } = this.props;
        let payload = {};
        dispatch({
            type: 'playlist/fetch',
            payload,
        });
        dispatch({
            type: 'playlist/fetchCity',
            payload,
        });
        dispatch({
            type: 'playlist/fetchScreen',
            payload,
        });
    }

    getFromValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;

            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }
            //console.log('postvalue', postvalue);
            if (postvalue.date && postvalue.date.length > 0) {
                const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
                const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
                postvalue = {
                    ...postvalue,
                    startSubDate,
                    endSubDate,
                };
                delete postvalue.date;
            }
        });
        return postvalue;
    };
    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = { ...obj };
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});
        const postvalue = this.getFromValue();
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'devtask/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
        });
        dispatch({
            type: 'devtask/fetch',
            payload: {},
        });
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'playlist/fetch',
            payload: postvalue,
        });
    };
    onExport = () => {
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'playlist/onExport',
            payload: postvalue,
            callback: src => {
                const link = document.createElement('a');
                link.download = 'filename';
                link.style.display = 'none';
                link.href = src;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
        });

    }
    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        const { devName } = this.props.match.params;
        const { cityCodes, playScreen } = this.props.playlist
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={5} sm={24}>
                        <FormItem>
                            {getFieldDecorator('date')(
                                <RangePicker
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                    // onChange={onChange}
                                    // onOk={onOk}
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('devUuid', {
                                rules: [{ required: false, message: '请输入设备名称!' }],
                            })(<Input placeholder="设备UUID" />)}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('vehLicplateNo', {
                                rules: [{ required: false, message: '请输入车牌号!' }],
                            })(<Input placeholder="车牌号" />)}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('vehCompany', {
                                rules: [{ required: false, message: '请输入公司名称!' }],
                                initialValue: devName === 'init' ? null : devName,
                            })(<Input placeholder="公司名称" />)}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={5} sm={24}>
                        <FormItem>
                            {getFieldDecorator('matId')(
                                < Select allowClear="true" placeholder="投放画面" style={{ width: '100%' }}>
                                    {playScreen.map((item, index) => (
                                        <Option value={item.code}>{item.name}</Option>
                                    ))}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('bindFlag')(
                                <Select allowClear="true" placeholder="绑定状态" style={{ width: '100%' }}>
                                    {setType.map((item, index) => (
                                        <Option value={index}>{item}</Option>
                                    ))}
                                </Select>
                            )}
                        </FormItem>
                    </Col>

                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('cityId')(
                                <Select allowClear="true" placeholder="所属城市" style={{ width: '100%' }}>
                                    {cityCodes.map((item, index) => (
                                        <Option value={item.code}>{item.name}</Option>
                                    ))}
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <span className={styles.submitButtons}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={this.onExport} style={{ marginLeft: 20 }}>
                                导出
                            </Button>
                        </span>
                    </Col>

                </Row>
            </Form >
        );
    }

    render() {
        // //console.log('task', this.props.task);
        const { playlist, loading } = this.props;
        const { playInfo, cityCodes, playScreen } = playlist
        const { selectedRows } = this.state;
        const columns = [
            {
                title: '日期',
                dataIndex: 'playDate',
            },
            {
                title: '设备UUID',
                dataIndex: 'devUuid',
            },
            {
                title: '车牌号',
                dataIndex: 'vehLicplate',
            },
            {
                title: '播放时长',
                dataIndex: 'playTimeLen',
            },
            {
                title: '投放里程',
                dataIndex: 'mileage',
            },
            {
                title: '可见人次',
                dataIndex: 'visibleCount',
            },
            {
                title: '所属公司',
                dataIndex: 'vehCompany',
            },

            {
                title: '主班司机',
                dataIndex: 'mainDriver',
            },

            {
                title: '司机电话',
                dataIndex: 'mdTelephone',

            },
        ];

        return (
            <PageHeaderLayout title="任务查询">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                        <Descriptions title="播放信息" bordered style={{ marginBottom: 20 }}>
                            <Descriptions.Item label="设备总数">{playInfo.totalDevCount}</Descriptions.Item>
                            <Descriptions.Item label="车辆总数">{playInfo.totalVehCount}</Descriptions.Item>
                            <Descriptions.Item label="播放总时长">{playInfo.totalPlayTimeLen}</Descriptions.Item>
                            <Descriptions.Item label="投放总里程">{playInfo.totalTiMileage}</Descriptions.Item>
                            <Descriptions.Item label="覆盖用户数" span={2}>{playInfo.converUserCount}</Descriptions.Item>
                            <Descriptions.Item label="播放画面" span={3}>
                                <img src={playInfo.matUrl} style={{ width: 400, height: 300 }}></img>
                            </Descriptions.Item>
                        </Descriptions>
                        <StandardTable
                            rowKey="setId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={playlist}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
            </PageHeaderLayout>
        );
    }
}
